package cn.liangjintang.webserver;


import java.io.File;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.List;

import cn.liangjintang.foldbrowerbundle.FoldBrowerDialog;
import cn.liangjintang.foldbrowerbundle.FoldDialogOKListener;
import cn.liangjintang.foldbrowerbundle.FoldViewBuilder;
import cn.liangjintang.webserver.webserver.NanoHTTPD;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;

import android.content.ClipData;
import android.content.ClipboardManager;
import android.net.ConnectivityManager;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class WebServerActivity extends Activity {
    NanoHTTPD nanoHTTPD;
    Button bt_ctrl, bt_setpath;
    TextView tv_address, tv_serverpath;
    ImageView iv;
    int port = 8080;
    File wwwroot;
    List<IP> hostaddres;
    int hostaddresIndex;

    boolean flag;
    String TAG = "MainActivity";
    Object receiver = null;
    int displayWidth;
    static final String serverrootpath = "服务器根目录:";
    static final int PERMISSION_WRITE_EXTERNAL_STORAGE_RequestCode = 2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Window window = this.getWindow();//https://blog.csdn.net/finddreams/article/details/78363031
        window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        setContentView(R.layout.activity_web_server);
        initView();
        initData();
        registerReceiver();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    void initView() {
        tv_address = (TextView) this.findViewById(R.id.textView_address);
        tv_serverpath = (TextView) this.findViewById(R.id.textView_path);
        iv = (ImageView) findViewById(R.id.iv1);
        bt_ctrl = (Button) findViewById(R.id.button1);
        bt_setpath = (Button) findViewById(R.id.button2);
        bt_ctrl.setOnClickListener(ocl);
        bt_setpath.setOnClickListener(ocl);
        tv_address.setOnClickListener(ocl);
        iv.setOnClickListener(ocl);
        iv.setOnLongClickListener(olcl);
        WindowManager wm = this.getWindowManager();
        DisplayMetrics outMetrics = new DisplayMetrics();
        wm.getDefaultDisplay().getMetrics(outMetrics);
        displayWidth = outMetrics.widthPixels < outMetrics.heightPixels ? //
                outMetrics.widthPixels : outMetrics.heightPixels;
    }

    void initData() {
        upDateAdressView();

        flag = isStart();
        Log.i(TAG, flag ? "已开始" : "未开始");
        if (flag) {
            bt_setpath.setVisibility(View.INVISIBLE);
            bt_ctrl.setText("停止");
            wwwroot = WebServer.webServer.wwwroot;
            port = WebServer.webServer.port;
            tv_serverpath.setText(serverrootpath + wwwroot.getAbsolutePath());
            return;
        }
        wwwroot = getSDCard();
        if (wwwroot != null)
            tv_serverpath.setText(serverrootpath + wwwroot.getAbsolutePath());
        else {
            tv_address.setText("文件系统异常,可能没有内存卡");
            bt_ctrl.setVisibility(View.INVISIBLE);
            bt_setpath.setVisibility(View.INVISIBLE);
            return;
        }
    }

    private final void showAddress(int index) {
        if (hostaddres.size() > 0) {

            hostaddresIndex = index % hostaddres.size();
            IP ip = hostaddres.get(hostaddresIndex);

            tv_address.setText("服务器IP:" + ip.getIp() //
                    + "\n          (点我进行网络设置)" //
                    +"\n连接类型:"+ip.getType()//
                    + "\n端口:" + port //
                    + "\n网址:" + ip.getHttpUrl("http://", port, "/"));
            Bitmap bitmap = createQRCodeBitmap(ip.getHttpUrl("http://", port, "/"));
            if (bitmap != null) {
                iv.setImageBitmap(bitmap);
            }
        } else {
            // Toast.makeText(this, "抱歉:没有可用的对外通讯IP", Toast.LENGTH_LONG).show();
            tv_address.setText("抱歉:暂时没有可用的对外通讯IP(点我进行网络设置)");
        }
    }

    private final void upDateAdressView() {
        hostaddres = getLocalIpAddress();
        showAddress(0);
    }

    final OnClickListener ocl = new OnClickListener() {

        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.button1:
                    serverCtrl();
                    break;
                case R.id.button2:
                    showDialog();
                    break;
                case R.id.textView_address:
                    setNetworkMethod();
                    break;
                case R.id.iv1:
                    showAddress(++hostaddresIndex);
                    break;
            }
        }

    };

    final View.OnLongClickListener olcl = new View.OnLongClickListener() {
        @Override
        public boolean onLongClick(View v) {
            if (hostaddres.size() > 0) {
                int index = hostaddresIndex % hostaddres.size();
                String text=hostaddres.get(index).getHttpUrl("http://",port,"/");
                //获取剪贴板管理器：
                ClipboardManager cm = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
                // 创建普通字符型ClipData
                ClipData mClipData = ClipData.newPlainText("Label", text);
                // 将ClipData内容放到系统剪贴板里。
                cm.setPrimaryClip(mClipData);
                Toast.makeText(WebServerActivity.this,"网址已复制到剪切板",Toast.LENGTH_SHORT).show();
            }
            return true;
        }
    };

    private void serverCtrl() {
        if (!flag) {
            bt_ctrl.setText("停止");
            startServer();
            bt_setpath.setVisibility(View.INVISIBLE);
        } else {
            bt_ctrl.setText("开始");
            stopServer();
            bt_setpath.setVisibility(View.VISIBLE);
        }
        flag = !flag;
    }

    private final void dirDialog(File file) {
        FoldBrowerDialog foldBrowerDialog = new FoldBrowerDialog();
        foldBrowerDialog.dirDialog(this, file, new FoldDialogOKListener() {
            @Override
            public void onOK(FoldViewBuilder foldViewBuilder) {
                File f = foldViewBuilder.selectedFileDir;
                if (f == null)
                    return;
                tv_serverpath.setText(serverrootpath + f.getAbsolutePath());
                wwwroot = f;
            }
        });
    }

    private void showDialog() {
        if (wwwroot == null) {
            Log.i("MAIN", "根目录异常");
            return;
        }
        dirDialog(wwwroot);
    }

    public void startServer() {
        Intent serviceIntent = new Intent(this, WebServer.class);
        Bundle bundle = new Bundle();
        bundle.putInt("PORT", port);
        bundle.putString("PATH", wwwroot.getAbsolutePath());
        serviceIntent.putExtras(bundle);
        startService(serviceIntent);

    }

    public final void stopServer() {
        Intent serviceIntent = new Intent(this, WebServer.class);
        stopService(serviceIntent);
    }

    private final boolean isStart() {
        int tag = 0;
        final String packageName = this.getApplicationInfo().packageName;
        final String mWebServerClassString = WebServer.class.getName();
        ActivityManager manager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
        List<ActivityManager.RunningServiceInfo> mServiceList = manager.getRunningServices(100);
        for (int i = 0; i < mServiceList.size(); i++) {
            String classString = mServiceList.get(i).service.getClassName();
            String packString = mServiceList.get(i).service.getPackageName();
            // Log.i(TAG, packString + "==" + classString);
            if (classString.equals(mWebServerClassString) && packString.equals(packageName)) {
                tag = 1;
                break;
            }
        }
        return tag == 1;
    }

    private final File getSDCard() {
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED))
            return Environment.getExternalStorageDirectory();
        return null;

    }

    @Override
    protected void onResume() {
        super.onResume();
        upDateAdressView();
        registerReceiver();
    }

    @Override
    protected void onPause() {
        unregisterReceiver();
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        unregisterReceiver();
        super.onDestroy();
    }

    // 生成QR图
    private final Bitmap createQRCodeBitmap(String text) {
        int size = displayWidth * 3 / 4 < 200 ? 200 : displayWidth * 3 / 4;
        int QR_WIDTH = size, QR_HEIGHT = size;
        try {
            // 需要引入core包
            Log.i(TAG, "生成的文本：" + text);
            if (text == null || "".equals(text) || text.length() < 1) {
                return null;
            }

            Hashtable<EncodeHintType, String> hints = new Hashtable<EncodeHintType, String>();
            hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
            // 比特矩阵
            BitMatrix bitMatrix = new QRCodeWriter().encode(text, BarcodeFormat.QR_CODE, QR_WIDTH, QR_HEIGHT, hints);
            int[] pixels = new int[QR_WIDTH * QR_HEIGHT];
            // 比特矩阵转颜色数组
            for (int y = 0; y < QR_HEIGHT; y++) {
                for (int x = 0; x < QR_WIDTH; x++) {
                    if (bitMatrix.get(x, y)) {
                        pixels[y * QR_WIDTH + x] = 0xff000000;// 黑点
                    } else {
                        pixels[y * QR_WIDTH + x] = 0x00ffffff;// 透明点,白点为0xffffffff
                    }

                }
            }

            // 解析颜色数组,其他的java平台可以选择其他的API
            Bitmap bitmap = Bitmap.createBitmap(QR_WIDTH, QR_HEIGHT, Bitmap.Config.ARGB_8888);

            bitmap.setPixels(pixels, 0, QR_WIDTH, 0, 0, QR_WIDTH, QR_HEIGHT);
            return bitmap;

        } catch (WriterException e) {
            e.printStackTrace();
            return null;
        }
    }

    public final List<IP> getLocalIpAddress() {
        List<IP> list = new ArrayList<>();
        try {
            // 遍历网络接口
            Enumeration<NetworkInterface> infos = NetworkInterface.getNetworkInterfaces();

            while (infos.hasMoreElements()) {
                // 获取网络接口
                NetworkInterface niFace = infos.nextElement();
                Enumeration<InetAddress> enumIpAddr = niFace.getInetAddresses();
                while (enumIpAddr.hasMoreElements()) {
                    InetAddress mInetAddress = enumIpAddr.nextElement();
                    if (mInetAddress.isSiteLocalAddress()||mInetAddress.isLinkLocalAddress()||IP.isCommonIP(mInetAddress))
                    {
                        list.add(new IP(mInetAddress));
                    }
                }
            }
        } catch (SocketException e) {
        }
        return list;
    }

    /*
     * 打开设置网络界面
     */
    public final void setNetworkMethod() {
        Intent intent = null;
        // 判断手机系统的版本 即API大于10 就是3.0或以上版本，不包括2.3.3
        if (android.os.Build.VERSION.SDK_INT > 10) {
            intent = new Intent(android.provider.Settings.ACTION_WIRELESS_SETTINGS);
        } else {
            intent = new Intent();
            ComponentName component = new ComponentName("com.android.settings",
                    "com.android.settings.WirelessSettings");
            intent.setComponent(component);
            intent.setAction("android.intent.action.VIEW");
        }
        startActivity(intent);
    }

    final Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            upDateAdressView();
        }

        ;
    };

    final BroadcastReceiver networkReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals(ConnectivityManager.CONNECTIVITY_ACTION)
                    || action.equals(WifiManager.WIFI_STATE_CHANGED_ACTION)) {
                Message message = new Message();
                message.what = 1;
                handler.sendMessage(message);
            }
        }
    };

    public void unregisterReceiver() {
        if (receiver != null) {
            unregisterReceiver(networkReceiver);
            receiver = null;
        }
    }

    ;

    public final void registerReceiver() {
        if (receiver == null) {
            IntentFilter mFilter = new IntentFilter();
            mFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
            mFilter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
            mFilter.setPriority(1000);
            receiver = networkReceiver;
            registerReceiver(networkReceiver, mFilter);
        }
    }

    ;
}

